package com.ly.hotel.spainterface.jg.adapter;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.util.Log;
import android.util.LruCache;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.ly.hotel.R;
import com.ly.hotel.spainterface.jg.bean.MassageItem;
import com.ly.hotel.spainterface.jg.utils.OkHttpUtils;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import de.greenrobot.event.EventBus;

/**
 * Created by ThinkPad on 2018/3/6.
 */

public class MassageItemCarAdapter extends BaseAdapter {

    private Context context;
    private List<MassageItem> list = new ArrayList<>();// 记录被删除的商品项
    private ListView shoppingCarListView;
    private final LruCache<String, Bitmap> mMemoryCache;
    private final Set<BitmapTask> tasksCollection;
    private String serverIP;
    private String serverPORT;
    private boolean isFirstEnter = true;
    private int mFirstVisibleItem;
    private int mVisibleItemCount;
    private List<MassageItem> massageItems;
    //private int num = 1;
    private int limitedGoodsNum;// 限制的数量

    public MassageItemCarAdapter(ListView shoppingCarListView,List<MassageItem> massageItems,
                                 Context context,String serverIP,String serverPORT,int limitedGoodsNum){
        this.context = context;
        this.shoppingCarListView = shoppingCarListView;
        tasksCollection = new HashSet<>();
        this.serverIP = serverIP;
        this.serverPORT = serverPORT;
        this.massageItems = massageItems;
        this.limitedGoodsNum = limitedGoodsNum;

        /*Iterator<Map.Entry<MassageItem,Integer>> it = map.entrySet().iterator();
        while (it.hasNext()){
            Map.Entry<MassageItem,Integer> entry = it.next();
            massageItemList.add(entry.getKey());
            massageItemNum.add(entry.getValue());
        }*/

        int maxMemory = (int) Runtime.getRuntime().maxMemory();// 获取应用可用的最大内存
        int cacheSize = maxMemory / 8;// 以应用的1/8作为缓存
        // 以图片的链接作为键，Bitmap对象作为值
        mMemoryCache = new LruCache<String, Bitmap>(cacheSize){
            @Override
            protected int sizeOf(String key, Bitmap value) {
                return value.getByteCount();
            }
        };

        setListViewScroll();
    }

    private void setListViewScroll() {
        shoppingCarListView.setOnScrollListener(new AbsListView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(AbsListView view, int scrollState) {
                if(scrollState == SCROLL_STATE_IDLE){
                    loadBitmaps(mFirstVisibleItem,mVisibleItemCount);
                }else{
                    cancelAllTask();
                }
            }

            @Override
            public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
                mFirstVisibleItem = firstVisibleItem;
                mVisibleItemCount = visibleItemCount;
                if(isFirstEnter && totalItemCount > 0){
                    loadBitmaps(mFirstVisibleItem, mVisibleItemCount);
                    isFirstEnter = false;
                }
                //Log.d("JgActivity","mFirstVisibleItem=" + mFirstVisibleItem + ",mVisibleItemCount=" + mVisibleItemCount + ",mVisableItemCount=" + totalItemCount);
            }
        });
    }

    public List<MassageItem> getList() {
        return list;
    }

    public List<MassageItem> getMassageItems() {
        return massageItems;
    }

    @Override
    public int getCount() {
        return massageItems.size();
    }

    @Override
    public Object getItem(int position) {
        return massageItems.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(final int position, View convertView, ViewGroup parent) {
        View view;
        final ViewHolder viewHolder;
        if(convertView == null){
            view = LayoutInflater.from(context).inflate(R.layout.jg_listview_car_item,null);
            viewHolder = new ViewHolder();
            viewHolder.goodsImage = view.findViewById(R.id.goods_image);
            viewHolder.goodsName = view.findViewById(R.id.goods_name);
            viewHolder.goodsPrice = view.findViewById(R.id.goods_price);
            viewHolder.goodsSub = view.findViewById(R.id.goods_sub);
            viewHolder.goodsAdd = view.findViewById(R.id.goods_add);
            viewHolder.goodsNum = view.findViewById(R.id.goods_num);
            viewHolder.shoppingItemDelete = view.findViewById(R.id.shopping_car_item_delete);
            view.setTag(viewHolder);
        }else{
            view = convertView;
            viewHolder = (ViewHolder) view.getTag();
        }

        final MassageItem massageItem = massageItems.get(position);
        final String massageItemId = massageItem.getId();
        // 商品数量
        final int[] num = {massageItem.getNum()};
        viewHolder.goodsName.setText(massageItem.getName());
        viewHolder.goodsPrice.setText("￥" + massageItem.getPrice() + "元/" + massageItem.getUnit());
        viewHolder.goodsNum.setText(num[0] + "");

        String imageUrl = "http://" + serverIP + ":" + serverPORT + "/upload/interface/consume/pic/" + massageItemId + ".jpg";
        viewHolder.goodsImage.setTag(imageUrl);
        setImageView(imageUrl,viewHolder.goodsImage);

        viewHolder.goodsSub.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(num[0] == 1){
                    Toast.makeText(context,"购买的商品数量不能低于1",Toast.LENGTH_SHORT).show();
                }else {
                    num[0]--;
                    viewHolder.goodsNum.setText(num[0] + "");
                    massageItem.setNum(num[0]);
                }
                EventBus.getDefault().post(new MassageItemEvent());
            }
        });

        viewHolder.goodsAdd.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Log.d("JgMainActivity", num[0] + "");
                if(limitedGoodsNum > 0){
                    if(num[0] == limitedGoodsNum){
                        Toast.makeText(context,"购买的商品数量不能高于" + limitedGoodsNum,Toast.LENGTH_SHORT).show();
                    }else{
                        num[0]++;
                        viewHolder.goodsNum.setText(num[0] + "");
                        massageItem.setNum(num[0]);
                    }
                }
                EventBus.getDefault().post(new MassageItemEvent());
            }
        });

        viewHolder.shoppingItemDelete.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                massageItem.setNum(1);// 重置为1
                massageItems.remove(massageItem);
                notifyDataSetChanged();
                EventBus.getDefault().post(new MassageItemEvent());
            }
        });

        return view;
    }

    class ViewHolder{
        ImageView goodsImage;
        TextView goodsName;
        TextView goodsPrice;
        Button goodsSub;
        Button goodsAdd;
        TextView goodsNum;
        TextView shoppingItemDelete;
    }

    // 设置图片
    public void setImageView(String url,ImageView imageView){
        Bitmap bitmap = getBitmapFromMemoryCache(url);
        if(bitmap != null){
            imageView.setImageBitmap(bitmap);
        }else{
            imageView.setImageResource(R.mipmap.jg_massage_item_default);// 设置默认图片
        }
    }

    // 将Bitmap添加到LrcCache缓存当中
    public void addBitmapToMemoryCache(String key,Bitmap bitmap){
        if(getBitmapFromMemoryCache(key) == null){
            mMemoryCache.put(key,bitmap);
        }
    }

    // 从LruCache缓存中获得Bitmap对象
    public Bitmap getBitmapFromMemoryCache(String key){
        return mMemoryCache.get(key);
    }

    // 加载Bitmap
    public void loadBitmaps(int mFirstVisibleItem,int mVisibleItemCount){
        try{
            for(int i = mFirstVisibleItem;i < mFirstVisibleItem + mVisibleItemCount;i ++){
                String imageUrl = "http://" + serverIP + ":" + serverPORT + "/upload/interface/consume/pic/" + massageItems.get(i).getId() + ".jpg";
                Bitmap bitmap = getBitmapFromMemoryCache(imageUrl);
                if(bitmap == null){// 缓存中没有
                    BitmapTask task = new BitmapTask();
                    tasksCollection.add(task);// 异步下载图片任务添加到集合当中
                    task.execute(imageUrl);// 开启下载任务
                }else{// 缓存中有
                    ImageView massageItemImage = shoppingCarListView.findViewWithTag(imageUrl);
                    if(massageItemImage != null && bitmap != null){
                        massageItemImage.setImageBitmap(bitmap);
                    }
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    // 取消所有异步任务
    public void cancelAllTask(){
        if(tasksCollection != null){
            for (BitmapTask task : tasksCollection) {
                task.cancel(false);
            }
        }
    }


    class BitmapTask extends AsyncTask<String,Void,Bitmap> {

        private String imageUrl;

        @Override
        protected Bitmap doInBackground(String... params) {
            imageUrl = params[0];
            Bitmap bitmap = downloadBitmap(imageUrl);
            if(bitmap != null){
                addBitmapToMemoryCache(imageUrl,bitmap);
            }
            return bitmap;
        }

        @Override
        protected void onPostExecute(Bitmap bitmap) {
            super.onPostExecute(bitmap);
            ImageView massageItemImage = shoppingCarListView.findViewWithTag(imageUrl);
            if(bitmap != null && massageItemImage != null){// 给ImageView设置图片
                massageItemImage.setImageBitmap(bitmap);
                tasksCollection.remove(this);// 移除当前任务
            }
        }

        private Bitmap downloadBitmap(String imageUrl){
            InputStream is = OkHttpUtils.getInstance().getImageResource(imageUrl);
            Bitmap bitmap = null;
            if(is != null){
                bitmap = decodeSampleBitmapFromStream(is,400,200);
            }
            return bitmap;
        }
    }

    // 将字节流转换为Bitmap对象
    public static Bitmap decodeSampleBitmapFromStream(InputStream is, int reqWidth, int reqHeight){
        final BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;// 设置为true，系统不会分配内存
        byte[] data = inputStreamToByteArray(is);
        BitmapFactory.decodeByteArray(data, 0, data.length, options);
        options.inSampleSize = caculateInSampleSize(options,reqWidth,reqHeight);
        options.inJustDecodeBounds = false;
        Bitmap bitmap = BitmapFactory.decodeByteArray(data, 0, data.length, options);
        return bitmap;
    }

    //计算inSampleSize值,reqWidth为ImageView要求的宽度
    public static int caculateInSampleSize(BitmapFactory.Options options, int reqWidth,int reqHeigh){
        // 获得资源图片的宽度和高度
        final int width = options.outWidth;
        final int height = options.outHeight;
        int inSampleSize = 1;
        if(width > reqWidth || height >reqHeigh){
            // 计算出资源图片和目标图片之间的比例
            final int heightRadio = Math.round((float) height / (float) reqHeigh);
            final int widthRadio = Math.round((float) width / (float) reqWidth);
            // 选择比例最小的作为inSampleSzie值
            inSampleSize = heightRadio < widthRadio ? heightRadio : widthRadio;
        }
        return inSampleSize;
    }

    // 将字节流转化为字节数组
    public static byte[] inputStreamToByteArray(InputStream inputStream) {
        try{
            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
            byte[] buff = new byte[1024];
            int len = 0;
            while ( (len = inputStream.read(buff)) != -1) {
                outputStream.write(buff, 0, len);
            }
            inputStream.close();
            outputStream.close();
            return outputStream.toByteArray();
        }catch (IOException e){
            e.printStackTrace();
        }
        return null;
    }
}
